package com.customization.unionpay.market.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.service.ApplicantUpdateService;
import com.customization.unionpay.market.util.PropUtils;
import com.engine.core.impl.Service;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class ApplicantUpdateServiceImpl extends Service implements ApplicantUpdateService {

    private static final Logger log = LoggerFactory.getLogger(ApplicantUpdateServiceImpl.class);

    @Override
    public synchronized boolean externalUpdateApplicant(String code, String actAuthCode, String newApplicant) throws Exception {
        boolean res = false;

        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();

        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            // 营销项目信息台账表单id
            int projectInfoFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_project_info_form_id"));
            // 获取营销项目信息台账主表表名
            String projectInfoMainTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(projectInfoFormId);
            log.info("获取营销项目信息台账主表表名："+projectInfoMainTableName);
            if (StrUtil.isNotBlank(projectInfoMainTableName)) {
                String sql = "select id from #{tableName} where PROJECT_CODE = ? ";
                sql = sql.replace("#{tableName}",projectInfoMainTableName);
                log.info("sql:"+sql);
                // 查询营销项目信息台账
                rs.executeQuery(sql,code);
                if (rs.next()) {
                    String act_pro_id = Util.null2String(rs.getString("id"));
                    // 营销活动事项台账表单id
                    int ledgerFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
                    // 营销活动事项台账主表表名
                    String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
                    log.info("营销活动事项台账主表表名："+ledgerTableName);
                    if (StrUtil.isNotBlank(ledgerTableName)) {
                        String sql1 = "select id from #{tableName} where yxpthdsqm = ? ";
                        sql1 = sql1.replace("#{tableName}",ledgerTableName);
                        log.info("sql1:"+sql1);
                        // 查询营销活动事项台账
                        rs.executeQuery(sql1,actAuthCode);
                        if (rs.next()) {
                            String act_led_id = Util.null2String(rs.getString("id"));
                            try {
                                // 转换申请人
                                String idByResourceLoginId = com.customization.unionpay.market.util.FormDataUtils.getIdByResourceLoginId(newApplicant);

                                // 修改营销项目信息台账
                                StringBuilder updateSql = new StringBuilder("update ");
                                updateSql.append(projectInfoMainTableName);
                                updateSql.append(" set zbr='");
                                updateSql.append(idByResourceLoginId);
                                updateSql.append( "' where id = '" );
                                updateSql.append(act_pro_id);
                                updateSql.append("' ");
                                log.info("updateSql:"+updateSql);
                                StringBuilder updateSql1 = new StringBuilder("update ");
                                updateSql1.append(ledgerTableName);
                                updateSql1.append(" set sqr='");
                                updateSql1.append(idByResourceLoginId);
                                updateSql1.append( "' where id = '" );
                                updateSql1.append(act_led_id);
                                updateSql1.append("' ");
                                log.info("updateSql1:"+updateSql1);
                                // 修改营销活动事项台账
                                rst.executeUpdate(updateSql.toString());
                                rst.executeUpdate(updateSql1.toString());
                                // 提交事务
                                boolean commit = rst.commit();
                                if (commit) {
                                    res = true;
                                }
                            } catch (Exception e) {
                                // 回滚
                                rst.rollback();
                                throw new Exception(e.getMessage());
                            }
                        } else {
                            throw new Exception("根据流水号查询营销活动事项台账为空！");
                        }
                    } else {
                        throw new Exception("根据营销活动事项台账formId查询数据库表名失败！");
                    }
                } else {
                    throw new Exception("根据流水号查询营销项目信息台账为空！");
                }
            } else {
                throw new Exception("根据营销项目信息台账formId查询数据库表名失败！");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return res;
    }


    @Override
    public synchronized boolean internalUpdateEventManager(String actAuthCode, String newApplicant) throws Exception {
        boolean res = false;

        RecordSet rs = new RecordSet();
        RecordSetTrans rst = new RecordSetTrans();

        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {
            // 营销活动事项台账表单id
            int ledgerFormId = Integer.parseInt(com.customization.unionpay.market.util.PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_activity_ledger_form_id"));
            // 营销活动事项台账主表表名
            String ledgerTableName = com.customization.unionpay.market.util.FormDataUtils.getTableName(ledgerFormId);
            log.info("营销活动事项台账主表表名："+ledgerTableName);
            if (StrUtil.isNotBlank(ledgerTableName)) {
                String sql = "select id from #{tableName} where yxpthdsqm = ? ";
                sql = sql.replace("#{tableName}",ledgerTableName);
                log.info("sql:"+sql);
                // 查询营销活动台账
                rs.executeQuery(sql,actAuthCode);
                if (rs.next()) {
                    String act_led_id = Util.null2String(rs.getString("id"));
                    try {
                        StringBuilder updateSql = new StringBuilder("update ");
                        updateSql.append(ledgerTableName);
                        updateSql.append(" set hdglr='");
                        updateSql.append(newApplicant);
                        updateSql.append( "' where id = '" );
                        updateSql.append(act_led_id);
                        updateSql.append("' ");

                        // 修改营销活动台账
                        rst.executeUpdate(updateSql.toString());
                        // 提交事务
                        boolean commit = rst.commit();
                        if (commit) {
                            res = true;
                        }
                    } catch (Exception e) {
                        // 回滚
                        rst.rollback();
                        throw new Exception(e.getMessage());
                    }
                } else {
                    throw new Exception("根据流水号查询营销活动事项台账失败！");
                }
            } else {
                throw new Exception("根据营销活动事项台账formId查询数据库表名失败！");
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return res;
    }

    @Override
    public JSONObject getChangeUserIdByCode(User user, String code) throws Exception {
        log.info("code:"+code);
        JSONObject userInfoByResourceCode = com.customization.unionpay.market.util.FormDataUtils.getUserInfoByResourceLoginId(code);
        log.info("userInfoByResourceCode:"+userInfoByResourceCode);
        JSONObject result = new JSONObject();
        if(userInfoByResourceCode != null ){
            List<JSONObject> datas = new ArrayList<>();
            String id = userInfoByResourceCode.getString("id");
            datas.add(userInfoByResourceCode);
            result.put("value",id);
            result.put("specialobj",datas);
        }else {
            throw new Exception("根据outkey获取人员信息异常！");
        }
        return result;
    }

    @Override
    public String getSqmCode(String code) throws Exception {
        List<String> list = new ArrayList<>();
        list.add(code);
        return com.customization.unionpay.market.util.CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(list);
    }

    @Override
    public String initSqmCode() throws Exception {

        // 请求数据
        JSONObject datas = new JSONObject();
        Date date = new Date();
        // 项目名称
        long time = date.getTime();
        datas.put("projectName", "测试项目"+time);
        // 结算方式  0-事后入账 1-全额入账
        datas.put("clearForm", "1");
        // 项目开始日期  YYYY-MM-DD
        datas.put("projectStartDate", new SimpleDateFormat("yyyy-MM-dd").format(date));
        // 项目结束日期  YYYY-MM-DD
        datas.put("projectEndDate", "2024-10-25");
        // 项目业务类型    立减活动-“0” 积分（普通-“1” 积分（消费送红包）-“2” 代金券-“3” 其他-“99”;
        datas.put("projectBusiType", "0");
        // 其他项目业务类型 选填，项目业务类型选择其他-99时必填。项目业务类型不为其他时不能填写
        datas.put("otherBusiType", "");
        // 项目充值金额
        datas.put("budgetValue", "10000.00");
        // 授权码出资类型      内部=”1” 外部=”2” 内外联合=”3”
        datas.put("contributionType", "1");
        // 银联出资金额          授权码出资类型为3时必填
        datas.put("unionpayValue", "10000.00");
        // 申请人
        datas.put("applicantUserId", "曾志阳");
        // 申请人分公司/部门
        datas.put("applicantOrgId", "00012900");
        // 预算授权码类型    0-实体 1-虚体
        datas.put("budgetAuthCodeType", "0");
        // 项目材料上传  非必填
        datas.put("filesId", "");
        // 备注 remark
        datas.put("remark", "测试项目"+time);


        return com.customization.unionpay.market.util.CloudFlashPaymentUtils.innerGenerateByBudgetCode(datas);
    }

    @Override
    public String updateSqm(String flag) throws Exception {
        // 请求数据
        JSONObject datas = new JSONObject();
        Date date = new Date();
        // 项目名称
        long time = date.getTime();

        // 调整原因	     data.adjustReason	String	1024		必填
        datas.put("adjustReason", "2024072916264000498501调整金额"+time);
        if("1".equals(flag)){
            // 调整类型	     data.adjustType	String	1		        必填    0-增加  1-减少  2-退款
            datas.put("adjustType", "0");
        }
        if("2".equals(flag)){
            // 调整类型	     data.adjustType	String	1		        必填    0-增加  1-减少  2-退款
            datas.put("adjustType", "1");
        }
        // 银联出资调整金额 data.adjustUnionpayValue	decimal(12,2)		　	必填。 内外联合类型的预算授权码该值不能大于调整金额的值。非内外联合类型的预算授权码该值该值传递0
        datas.put("adjustUnionpayValue", "0.00");
        // 调整金额	     data.adjustValue	decimal(12,2)			必填
        datas.put("adjustValue", "500.00");
        // 待审核资金量	 data.fundValue				必填      该值为已审核资金量值加上调整金额的量
        datas.put("fundValue", "10500.00");
        // 预算授权码	     data.budgetAuthCode	String	30		必填
        datas.put("budgetAuthCode", "2024072916264000498501");

        return com.customization.unionpay.market.util.CloudFlashPaymentUtils.innerAdjustByBudgetCode(datas);
    }

    @Override
    public String clearJiZ() throws Exception {
        String requestSysCode = PropUtils.BB_LOG.getPropValue("marketSubject", "requestSysCode");

        String bussSn = UUID.randomUUID().toString();

        List<JSONObject> params = new ArrayList<>();

        JSONObject res1 = new JSONObject();
        // 币种        bussCurr           "CNY"
        res1.put("bussCurr","CNY");
        // 汇率	    chgRate             1.00
        res1.put("chgRate","1.00");
        // 记账类型	finType            "03":发生
        res1.put("finType","03");
        // 记账类别	occurTp            "01": 普通记账
        res1.put("occurTp","01");
        // 附言	    remark
        res1.put("remark","");
        // 记账方向	occurDirect        "1":借  "2":贷
        res1.put("occurDirect","1");
        // 业务流水号	bussSn
        res1.put("bussSn",bussSn);
        // 业务账号	acctNo
        res1.put("acctNo","00000001");
        // 业务金额     bussAt
        res1.put("bussAt", "200.00");


        JSONObject res2 = new JSONObject();
        // 币种        bussCurr           "CNY"
        res2.put("bussCurr","CNY");
        // 汇率	    chgRate             1.00
        res2.put("chgRate","1.00");
        // 记账类型	finType            "03":发生
        res2.put("finType","03");
        // 记账类别	occurTp            "01": 普通记账
        res2.put("occurTp","01");
        // 附言	    remark
        res2.put("remark","");
        // 记账方向	occurDirect        "1":借  "2":贷
        res2.put("occurDirect","2");
        // 业务流水号	bussSn
        res2.put("bussSn",bussSn);
        // 业务账号	acctNo
        res2.put("acctNo","202407291626400049850102");
        // 业务金额     bussAt
        res2.put("bussAt", "200.00");

        params.add(res1);
        params.add(res2);

        return com.customization.unionpay.market.util.ClearBusAccSystemUtils.businessAccountBookkeeping(params, requestSysCode );
    }

    @Override
    public String createInn() throws Exception {

        long time = new Date().getTime();

        JSONObject mpmKeyJson = new JSONObject();
        // 是 业务流水号	字母数字组合
        mpmKeyJson.put("mpmKey",time);
        // 	是	账套号	字母数字组合
        mpmKeyJson.put("sfbCd","00001");
        // 	是	付款业务账号	数字
        mpmKeyJson.put("bussAcctNo","0001015000000034505");
        //  是	币种 (人民币：CNY)	字母数字组合
        mpmKeyJson.put("currCd","CNY");
        //	是	金额（单位为分）	数字
        mpmKeyJson.put("bussAt",10000);
        //	否	汇率
        mpmKeyJson.put("exchangeRate","");
        //	是	收款账户账号	数字
        mpmKeyJson.put("rcvBankAcctNo","001129313007");
        //	是	收款账户账号名称
        mpmKeyJson.put("rcvBankAcctNm","中国人民银行永年县支行");
        //	是	收款账户账号行号	数字
        mpmKeyJson.put("rcvBankAcctBankNo", "12");
        //	是	收款账户账号行名
        mpmKeyJson.put("rcvBankAcctBankNm", "12");
        //	否	附言
        mpmKeyJson.put("transPtscpt","测试");
        //	是	营销活动授权码	字母数字组合
        mpmKeyJson.put("marketAuthorCode","2024072916264000498501");

        return com.customization.unionpay.market.util.InnovativeSettlementUtils.createWorkFlow(mpmKeyJson);
    }

    @Override
    public String selectPstate(String code) throws Exception {
        List<String> codes = new ArrayList<>();
        codes.add(code);
        JSONObject params = new JSONObject();
        params.put("mpmKeyList",codes);
        return com.customization.unionpay.market.util.InnovativeSettlementUtils.queryPayState(params);
    }

    @Override
    public String getJJSXIdByCode(User user, String code) throws Exception {
        return com.customization.unionpay.market.util.FormDataUtils.geJJSXIdByCode(code);
    }

}
